package me.jzn.alib.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import me.jzn.core.exceptions.ShouldNotRunHereException;
import me.jzn.core.utils.CommUtil;

public class DateUtil {
    private static final String DF_MONTH = "yyyyMM";
    private static final String DF_DAY = "yyyyMMdd";
    // 线程不安全
    //    private static final DateFormat DF_MONTH = new SimpleDateFormat("yyyyMM");
    //    private static final DateFormat DF_DAY = new SimpleDateFormat("yyyyMMdd");
    public static final long ADAY = 24 * 60 * 60 * 1000;
    public static final long AYEAR = 365L * 24 * 60 * 60 * 1000;
    public static final long AWEEK = ADAY * 7;

    public static Date addYear(Date date, int year) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(date);
        cld.add(Calendar.YEAR, year);
        return cld.getTime();
    }

    public static int deltaDate(Date d1, Date d2) {
        Date start1 = getDateStart(d1);
        Date start2 = getDateStart(d2);
        return (int) ((start2.getTime() - start1.getTime()) / ADAY);
    }


    public static Date getDateStart(Date d) {
        Calendar cld = Calendar.getInstance();
        cld.setTime(d);
        cld.set(Calendar.HOUR_OF_DAY, 0);
        cld.set(Calendar.MINUTE, 0);
        cld.set(Calendar.SECOND, 0);
        cld.set(Calendar.MILLISECOND, 0);
        return cld.getTime();
    }

    public static boolean isToday(Date date) {
        DateFormat df_day = new SimpleDateFormat(DF_DAY);
        return df_day.format(date).equals(df_day.format(new Date()));
    }

    public static boolean sameDay(Date d1, Date d2) {
        DateFormat df_day = new SimpleDateFormat(DF_DAY);
        return df_day.format(d1).equals(df_day.format(d2));
    }

    public static boolean sameMonth(Date d1, Date d2) {
        DateFormat df_month = new SimpleDateFormat(DF_MONTH);
        return df_month.format(d1).equals(df_month.format(d2));
    }

    public static String format(String fmt, Date date) {
        if (date == null) {
            return null;
        }
        return new SimpleDateFormat(fmt).format(date);
    }

    public static Date parse(String fmt, String dateStr) {
        if (dateStr == null || dateStr.length() == 0) {
            return null;
        }
        try {
            return new SimpleDateFormat(fmt).parse(dateStr);
        } catch (ParseException e) {
            throw new ShouldNotRunHereException(String.format("parse date error:%s!=%s", fmt, dateStr));
        }
    }

    // try null/long/yyyy-MM-dd HH:mm:ss/
    public static Date parse(String dateStr) {
        if (dateStr == null || dateStr.length() == 0) {
            return null;
        }
        try {
            return new Date(Long.parseLong(dateStr));
        } catch (NumberFormatException e) {
            return CommUtil.parseDate(dateStr);
        }
    }
}
